package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.UserAccount;
import model.type.SubjectAttributeType;
import model.type.SubjectType;
import search.SearchAttribute;
import search.SearchString;
import db.ImbiConnection;

public class SearchController extends HttpServlet{

	
	private static final long serialVersionUID = 1L;
	
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");		
		if(u != null){		
			ArrayList<SearchAttribute> atrbs = new ArrayList<SearchAttribute>();
			for(Entry<String, String[]> e: request.getParameterMap().entrySet()){
				try{
					int key = Integer.parseInt(e.getKey());
					if(!e.getValue()[0].isEmpty())atrbs.add(new SearchAttribute(key, e.getValue()[0]));
				} catch(NullPointerException | NumberFormatException ex){	}				
			}				
			
			SearchString search = new SearchString(				
				request.getParameter("name"),
				request.getParameter("type"),
				request.getParameter("country"),
				request.getParameter("county"),
				request.getParameter("city"),
				request.getParameter("address"),
				request.getParameter("index"),
				request.getParameter("contact"),
				atrbs
			);
			
			request.setAttribute("search_string", search);
			
			if(search.getType() == SubjectType.ENTERPRISE || search.getType() == SubjectType.CUSTOMER){
				request.setAttribute("result_enterprise", ImbiConnection.getEnterpriseDAO().search(search));						
			} 
			
			if(search.getType() == SubjectType.PERSON || search.getType() == SubjectType.CUSTOMER || search.getType() == SubjectType.EMPLOYEE){
				request.setAttribute("result_person", ImbiConnection.getPersonDAO().search(search));
			}
			
			doGet(request, response);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");		
		if(u != null){		
			request.setAttribute("customer_attributes", SubjectAttributeType.getAll(SubjectType.CUSTOMER));
			request.setAttribute("enterprise_attributes", SubjectAttributeType.getAll(SubjectType.ENTERPRISE));
			request.setAttribute("employee_attributes", SubjectAttributeType.getAll(SubjectType.EMPLOYEE));
			request.setAttribute("person_attributes", SubjectAttributeType.getAll(SubjectType.PERSON));
			request.getRequestDispatcher("/WEB-INF/searchform.jsp").forward(request, response);	
		}
	}	
}
